//
//  SWAlbumViewController.swift
//  ChildStory
//
//  Created by linhan on 16/8/22.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWAlbumViewController: SWBaseViewController,SWAssetsLibraryHelperDelegate,UICollectionViewDataSource,UICollectionViewDelegate,CollectionViewCellDelegate,ScrollTabBarDelegate
{
    private class SWPhotoSection:NSObject
    {
        var photos:[SWALPhoto] = []
        var date:Date
        var title:String = ""
        var y:CGFloat = 0
        
        init(date:Date, photos:[SWALPhoto])
        {
            self.date = date
            self.photos = photos
            super.init()
            let nsdate = date as NSDate
            title = "\(nsdate.year())-\(nsdate.month())-\(nsdate.day())"
        }
        
        func contains(localIdentifier:String) -> Bool
        {
            return photos.contains(where: {$0.localIdentifier == localIdentifier})
        }
    }
    
    //
    private enum AlbumSourceType
    {
        case app
        case local
    }
    
    private var _sourceType:AlbumSourceType = .app
    
    //分类列表
    private var _selectedStageIndex:Int = 0
    private var _selectedCategoryIndexPath:IndexPath = IndexPath.zero
    private var _categories:[SWKidEvent] = []
    
    //用户相册
    private var _photos:[SWPhotoSection] = []
    //系统相册
    private var _localPhotos:[SWPhotoSection] = []
    
    private var _photoSource:[SWPhotoSection]{
        return _sourceType == .app ? _photos : _localPhotos
    }
    
    private let VCollectionViewTag:Int = 1
    private let ContentLeftMargin:CGFloat = 12
    private let ContentRightMargin:CGFloat = 12
    
    private var _tabBar:ScrollTabBar?
    private var _collectionView:UICollectionView?
    private var _hCollectionView:UICollectionView?
    private var _toolbar:UIView = UIView()
    private var _switchBtn:UIButton = UIButton(type: .custom)
    private var _titleLabel:UILabel = UILabel()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    
    deinit
    {
        print("DEINIT SWAlbumViewController")
    }
    
    private func setup()
    {
        title = "相册"
        view.backgroundColor = UIColor(hex: 0xf5f5f5)
        automaticallyAdjustsScrollViewInsets = false
        
        return
        
        //createNavigationRightButton("实体相册", target: self, action: #selector(bookBtnTapped))
        
        _tabBar = ScrollTabBar(frame: CGRectMake(0, navigationBarBottom, view.width, 40))
        _tabBar?.font = UIFont.systemFont(ofSize: 14)
        _tabBar?.itemSpacing = 30
        _tabBar?.alignment = .center
        _tabBar?.selectedColor = UIColor(hex: 0x323131)
        _tabBar?.unselectedColor = UIColor(hex: 0xa0a0a0)
        _tabBar?.delegate = self
        view.addSubview(_tabBar!)
        
        let line = UIView()
        line.backgroundColor = UIColor(hex: 0xe2e2e2)
        line.frame = CGRectMake(0, _tabBar?.bottom ?? 0, view.width, 1)
        view.addSubview(line)
        
        createHCollectionView(y:line.bottom)
        
        createToolbar(y: (_hCollectionView?.bottom ?? 0) + 7)
        
        createVCollectionView(y: _toolbar.bottom)
        
        SWAssetsLibraryHelper.shared().addDelegate(self)
        
        loadData()
    }
    
    private func loadData()
    {
        let stages:[SWStage] = SWConfigManager.sharedManager().stages
        let items:[String] = stages.map({$0.title ?? ""})
        _tabBar?.titleItems = items
        _tabBar?.selectedIndex = _selectedStageIndex
        _categories = stages.valueAt(_selectedStageIndex)?.events?.flatMap({$0 as? SWKidEvent}) ?? []
        _hCollectionView?.reloadData()
        if stages.count > 0
        {
            _hCollectionView?.selectItem(at: IndexPath.zero, animated: false, scrollPosition: .centeredHorizontally)
        }
        
        
        //未分类过的图片
        let assets = SWAssetsManager.sharedManager().assets
        let localIdentifiers:[String] = assets.filter({$0.valid && !$0.classified}).map({$0.localID})
        let photos = SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: localIdentifiers)
        _photos = categoryAndSort(photos: photos)
        
        setSourceType(_sourceType)
    }
    
    //水平分类CollectionView
    private func createHCollectionView(y:CGFloat)
    {
        let CellGrid:CGFloat = 5
        let Count:CGFloat = 2
        let itemWidth:CGFloat = (view.width - (Count * CellGrid)) / Count
        let itemSize = CGSizeMake(itemWidth, itemWidth)
        let insetsBottom:CGFloat = 23
        let collectionViewHeight = max(itemSize.height + insetsBottom, 182)
        let collectionViewFrame = CGRectMake(0, y, view.width, collectionViewHeight)
        
        let inset:CGFloat = (collectionViewFrame.width - itemSize.width) * 0.5
        let layout:UICollectionViewFlowLayout = SWGalleryLayout()
        layout.itemSize = itemSize
        layout.minimumLineSpacing = CellGrid
        layout.sectionInset = UIEdgeInsetsMake(0, inset, insetsBottom, inset)
        layout.scrollDirection = .horizontal
        
        _hCollectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: layout)
        _hCollectionView?.backgroundColor = UIColor.white
        _hCollectionView?.register(SWCategoryCollectionCell.self, forCellWithReuseIdentifier: "SWCategoryCollectionCell")
        _hCollectionView?.dataSource = self
        _hCollectionView?.delegate = self
        view.addSubview(_hCollectionView!)
    }
    
    private func createVCollectionView(y:CGFloat)
    {
        let numOfHorizontal:Int = 4
        let Grid:CGFloat = 3
        let cellWidth:CGFloat = (view.width - ContentLeftMargin - ContentRightMargin - CGFloat(numOfHorizontal - 1) * Grid) / CGFloat(numOfHorizontal)
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(cellWidth, cellWidth)
        //横向最小间隔
        layout.minimumInteritemSpacing = Grid
        //纵向最小间隔
        layout.minimumLineSpacing = Grid
        layout.sectionInset = UIEdgeInsetsMake(8, ContentLeftMargin, 8, ContentRightMargin)
        
        let collectionViewFrame = CGRectMake(0, y, view.width, view.height - y)
        _collectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: layout)
        _collectionView?.tag = VCollectionViewTag
        _collectionView?.backgroundColor = UIColor.white
        _collectionView?.alwaysBounceVertical = true
        _collectionView?.register(SWAlbumCollectionCell.self, forCellWithReuseIdentifier: "SWAlbumCollectionCell")
        _collectionView?.register(CollectionSectionHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView")
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        view.addSubview(_collectionView!)
    }
    
    private func createToolbar(y:CGFloat)
    {
        _toolbar.frame = CGRectMake(0, y, view.width, 40)
        _toolbar.backgroundColor = UIColor.white
        view.addSubview(_toolbar)
        
        _titleLabel.frame = CGRectMake(ContentLeftMargin, 12, 120, 18)
        _titleLabel.font = UIFont.systemFont(ofSize: 14)
        _titleLabel.textColor = UIColor(hex: 0x7d7d7d)
        _toolbar.addSubview(_titleLabel)
        
        let LabelLeftMargin:CGFloat = 6
        _switchBtn.setImage(UIImage(named:"album_btn_switch"), for: .normal)
        _switchBtn.setTitleColor(UIColor(hex:0x7d7d7d), for: .normal)
        _switchBtn.setTitle("咿呀相册", for: .normal)
        _switchBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        _switchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, LabelLeftMargin, 0, 0)
        _switchBtn.sizeToFit()
        _switchBtn.width += LabelLeftMargin
        _switchBtn.center = CGPointMake(_toolbar.width - _switchBtn.width * 0.5 - 12, _toolbar.height * 0.5)
        _switchBtn.addTarget(self, action: #selector(switchBtnTapped), for: .touchUpInside)
        _toolbar.addSubview(_switchBtn)
        
        let line:UIView = UIView()
        line.backgroundColor = UIColor(hex: 0xe2e2e2)
        line.frame = CGRectMake(0, _toolbar.height - 1, _toolbar.width, 1)
        _toolbar.addSubview(line)
    }
    
    private var _localPhotosFetched:Bool = false
    private func fetchLocalPhotos()
    {
        _localPhotosFetched = true
        SWAssetsLibraryHelper.shared().requestAuthorization{status in
            if status == .Authorized
            {
                SWAssetsLibraryHelper.shared().fetchAlbum()
            }
            else
            {
                
            }
        }
    }
    
    //分类排序
    private func categoryAndSort(photos:[SWALPhoto]) -> [SWPhotoSection]
    {
        //用时间做key,[20160101:[MUVideo]]
        var dic:[Double:[SWALPhoto]] = [:]
        for photo in photos
        {
            let date:NSDate = (photo.creationDate ?? Date()) as NSDate
            let dayDate:NSDate = NSDate(year: date.year(), month: date.month(), day: date.day())
            let time:Double = dayDate.timeIntervalSince1970
            dic[time] = dic[time] ?? []
            dic[time]?.append(photo)
        }
        
        var sections:[SWPhotoSection] = []
        for (time, photo) in dic
        {
            let date = Date(timeIntervalSince1970: time)
            let section:SWPhotoSection = SWPhotoSection(date: date, photos: photo)
            sections.append(section)
        }
        sections.sort(by: {$0.date.timeIntervalSince1970 > $1.date.timeIntervalSince1970})
        return sections
    }
    
    private func setSourceType(_ type:AlbumSourceType)
    {
        let label:String = type == .app ? "咿呀相册" : "系统相册"
        _switchBtn.setTitle(label, for: .normal)
        _sourceType = type
        
        
        if type == .local && !_localPhotosFetched
        {
            fetchLocalPhotos()
        }
        else
        {
            if let collectionView = _collectionView
            {
                collectionView.reloadData()
                photoCollectionViewEndScrolling(collectionView)
            }
        }
        
    }
    
    //移动照片进行归类
    private func movePhoto(from srcIndex:IndexPath, to dstIndex:IndexPath)
    {
        //print("movePhoto", srcIndex, dstIndex)
        //如果某个section只有一张图片，则删除整个section
        let deleteSection:Bool = (_photoSource.valueAt(srcIndex.section)?.photos.count ?? 0) == 1
        let photo:SWALPhoto? = _photoSource.valueAt(srcIndex.section)?.photos.valueAt(srcIndex.row)
        if _sourceType == .app
        {
            if deleteSection
            {
                _photos.removeAtIndexSafely(srcIndex.section)
            }
            else
            {
                _photos.valueAt(srcIndex.section)?.photos.removeAtIndexSafely(srcIndex.row)
            }
        }
        else
        {
            if deleteSection
            {
                _localPhotos.removeAtIndexSafely(srcIndex.section)
            }
            else
            {
                _localPhotos.valueAt(srcIndex.section)?.photos.removeAtIndexSafely(srcIndex.row)
            }
        }
        
        if let event = _categories.valueAt(dstIndex.row),
           let photo = photo
        {
            SWAssetsManager.sharedManager().addAsset(localID: photo.localIdentifier, event: event)
        }
        
        if deleteSection
        {
            if srcIndex.section == 0
            {
                _collectionView?.reloadData()
            }
            else
            {
                _collectionView?.deleteSections(IndexSet([srcIndex.section]))
            }
        }
        else
        {
            _collectionView?.deleteItems(at: [srcIndex])
        }
        
    }
    
    //MARK ============================================================================================
    //==============================     UICollectionViewDelegate  ===============================
    //=================================================================================================
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int
    {
        return collectionView.tag == VCollectionViewTag ? _photoSource.count : 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return collectionView.tag == VCollectionViewTag ?
            (_photoSource.valueAt(section)?.photos.count ?? 0) :
            _categories.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell:UICollectionViewCell
        if collectionView.tag == VCollectionViewTag {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SWAlbumCollectionCell", for: indexPath) as! SWAlbumCollectionCell
            (cell as? SWAlbumCollectionCell)?.delegate = self
            if let photo = _photoSource.valueAt(indexPath.section)?.photos.valueAt(indexPath.row)
            {
                (cell as? SWAlbumCollectionCell)?.photo = photo
                photo.fetchThumbnail()
            }
        }
        else
        {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SWCategoryCollectionCell", for: indexPath) as! SWCategoryCollectionCell
            (cell as? SWCategoryCollectionCell)?.event = _categories.valueAt(indexPath.row)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
    {
        //print("kind", kind, indexPath.section)
        var supplementaryView:CollectionSectionHeader?
        if kind == UICollectionElementKindSectionHeader
        {
            supplementaryView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier:"headerView", for:indexPath) as? CollectionSectionHeader
            supplementaryView?.title = _photoSource.valueAt(indexPath.section)?.title ?? ""
        }
        return supplementaryView ?? UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
    {
        if collectionView.tag == VCollectionViewTag && section > 0
        {
            return CGSizeMake(0, 50)
        }
        return CGSize.zero
    }
    
    
    func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath)
    {
        if collectionView.tag == VCollectionViewTag
        {
            _photoSource.valueAt(indexPath.section)?.y = view.frame.origin.y
            photoCollectionViewEndScrolling(collectionView)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath)
    {
        if collectionView.tag == VCollectionViewTag
        {
            _photoSource.valueAt(indexPath.section)?.y = view.frame.origin.y
            photoCollectionViewEndScrolling(collectionView)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        if collectionView.tag == VCollectionViewTag
        {
            var photos:[SWALPhoto] = []
            let sections = _photoSource
            for section in sections
            {
                photos += section.photos
            }
            var index:Int = 0
            if let photo = sections.valueAt(indexPath.section)?.photos.valueAt(indexPath.row),
               let aIndex = photos.index(where: {$0.localIdentifier == photo.localIdentifier})
            {
                index = aIndex
            }
            let viewController = SWPhotosDetailViewController(photos: photos)
            viewController.index = index
            navigationController?.pushViewController(viewController, animated: true)
        }
        else
        {
            if _selectedCategoryIndexPath == indexPath
            {
                if let event = _categories.valueAt(indexPath.row)
                {
                    let viewController = SWEventDetailViewController()
                    viewController.eventID = event.eventID ?? ""
                    viewController.showPhoto = true
                    navigationController?.pushViewController(viewController, animated: true)
                }
            }
            else
            {
                _selectedCategoryIndexPath = indexPath
                collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
            }
        }//end CategoryCollectionView
    }
    
    func collectionViewCell(_ cell:UICollectionViewCell, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Add
        {
            
            if let sourceIndexPath = _collectionView?.indexPath(for: cell),!_categoryCollectionViewScrolling
            {
                movePhoto(from: sourceIndexPath, to: _selectedCategoryIndexPath)
                if let cursor = cell.snapshotView(afterScreenUpdates: false)
                {
                    let startFrame = cell.superview?.convert(cell.frame, to: view) ?? CGRect(origin: view.center, size: cell.frame.size)
                    cursor.frame = startFrame
                    UIApplication.shared.keyWindow?.addSubview(cursor)
                    let targetCenter = _hCollectionView?.center ?? CGPoint.zero
                    UIView.animate(withDuration: 0.3, animations: {
                        cursor.center = targetCenter
                        cursor.alpha = 0
                        cursor.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
                    }, completion: {finish in
                        cursor.removeFromSuperview()
                    })
                }
            }//end sourceIndexPath
        }
    }
    
    private var _categoryCollectionViewScrolling:Bool = false
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView)
    {
        if !(scrollView.tag == VCollectionViewTag)
        {
            _categoryCollectionViewScrolling = true
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
    {
        if scrollView.tag == VCollectionViewTag
        {
            photoCollectionViewEndScrolling(scrollView)
        }
        else
        {
            categoryCollectionViewEndScrolling()
        }
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)
    {
        if scrollView.tag == VCollectionViewTag
        {
            photoCollectionViewEndScrolling(scrollView)
        }
        else
        {
            categoryCollectionViewEndScrolling()
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)
    {
        if scrollView.tag == VCollectionViewTag
        {
            photoCollectionViewEndScrolling(scrollView)
        }
    }
    
    private func photoCollectionViewEndScrolling(_ scrollView: UIScrollView)
    {
        let offsetY:CGFloat = scrollView.contentOffset.y
        var section:SWPhotoSection? = _photoSource.valueAt(0)
        for aSection in _photoSource
        {
            if offsetY <= aSection.y
            {
                break
            }
            section = aSection
        }
        
        _titleLabel.text = section?.title ?? ""
    }
    
    private func categoryCollectionViewEndScrolling()
    {
        _categoryCollectionViewScrolling = false
        if let collectionView = _hCollectionView,
            let indexPath = collectionView.indexPathForItem(at: collectionView.bounds.center)
        {
            _selectedCategoryIndexPath = indexPath
            _hCollectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)
        }
    }
    
    //MARK ================================= ScrollTabBarDelegate =========================
    func scrollTabBar(_ tabBar: ScrollTabBar, didSelectIndex index: Int)
    {
        let stages = SWConfigManager.sharedManager().stages
        _selectedStageIndex = index
        _categories = stages.valueAt(_selectedStageIndex)?.events?.flatMap({$0 as? SWKidEvent}) ?? []
        _hCollectionView?.reloadData()
        _hCollectionView?.selectItem(at: IndexPath.zero, animated: false, scrollPosition: .centeredHorizontally)
    }
    
    //MARK ============================================================================================
    //==============================     SWAssetsLibraryHelperDelegate  ===============================
    //=================================================================================================
    
    //相册获取完成
    func albumFetchComplete(_ album:[SWALAlbum], defaultAlbum:SWALAlbum?)
    {
        if let defaultAlbum = defaultAlbum
        {
            SWAssetsLibraryHelper.shared().fetchPhotoList(album: defaultAlbum)
        }
    }
    
    //相片获取
    func photosFetchComplete(_ photos:[SWALPhoto])
    {
        //过滤掉咿呀相册已经有的
        let assets = SWAssetsManager.sharedManager().assets
        let localIdentifiers:[String] = assets.filter({$0.valid}).map({$0.localID})
        
        let t1:Double = Date().timeIntervalSince1970
        //let aPhotos = photos.filter({photo in !_photos.contains(where: {$0.contains(localIdentifier: photo.localIdentifier)})})
        let aPhotos:[SWALPhoto] = photos.filter({photo in !localIdentifiers.contains(photo.localIdentifier)})
        
        print("过滤耗时:", Date().timeIntervalSince1970 - t1)
        _localPhotos = categoryAndSort(photos: aPhotos)
        if let collectionView = _collectionView
        {
            collectionView.reloadData()
            photoCollectionViewEndScrolling(collectionView)
        }
    }
    
    
    //MARK ============================================================================================
    //==============================                Selector            ===============================
    //=================================================================================================
    
    
    @objc private func switchBtnTapped()
    {
        setSourceType(_sourceType == .app ? .local : .app)
    }
    
    @objc private func bookBtnTapped()
    {
        navigationController?.pushViewController(SWBookViewController(), animated: true)
    }
    
}


//MARK ============================================================================================
//==============================       CollectionSectionHeader      ===============================
//=================================================================================================

fileprivate class CollectionSectionHeader:UICollectionReusableView
{
    private var _timeLabel:UILabel = UILabel()
    
    var title:String = ""{
        didSet{
            _timeLabel.text = title
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        _timeLabel.textColor = UIColor.darkGray
        _timeLabel.font = UIFont.systemFont(ofSize: 14)
        _timeLabel.frame = CGRectMake(12, 29, 120, 18)
        _timeLabel.textColor = UIColor(hex: 0x7d7d7d)
        addSubview(_timeLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
